package cn.lj.security;

import cn.hutool.json.JSONUtil;
import cn.lj.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @file: jwtAuthenticationEntryPoint
 * @version: 1.0
 * @Description: 定义认证失败处理类
 * 代码目的，作用，如何工作
 * @author: 李津
 * @date: 2021-05-22 12:33
 * 本代码要注意的事项、备注事项等
 */
@Slf4j
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    /**
     * 当认证失败的时候会进入AuthenticationEntryPoint，自定义认证失败返回的数据
     * @param request
     * @param response
     * @param authException
     * @throws IOException
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        log.info("认证失败！未登录！");
        response.setContentType("application/json;charset=UTF-8");
        //未认证
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        ServletOutputStream outputStream = response.getOutputStream();
        Result result = Result.fail("请先登录！");
        outputStream.write(JSONUtil.toJsonStr(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
